﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;

namespace SZWCFBatteryService
{
    class DataBaseOperate
    {
        private static string constr = "Data Source =.;Initial Catalog =SZ_DataBase;User Id = sa;Password = shidai888; pooling=false;";
        //string.Format("data source={0};database={1};user id={2};password={3}", ConfigOperate.ReadIniKeys("DataBase",
        //    "DataSource", configPath), ConfigOperate.ReadIniKeys("DataBase", "DataBase", configPath), ConfigOperate.ReadIniKeys("DataBase",
        //    "UserId", configPath), ConfigOperate.ReadIniKeys("DataBase", "PassWord", configPath));
        //private static string constr = "data source=localhost;database=J02GZXT100001;user id=sa;password=shidai888";
        private static SqlConnection conn;
        private static SqlCommand cmd;

        #region 连接数据库
        // 摘要: 
        //     此方法用于连接数据库。
        private void connet()
        {
            conn = new SqlConnection(constr);
            cmd = new SqlCommand();
            cmd.Connection = conn;
        }
        #endregion

        #region 加载数据
        // 摘要: 
        //     此方法用于查询加载数据库数据。
        //
        // 参数: 
        //   sql:
        //     查询数据库的SQL语句。
        //
        // 返回结果: 
        //   dt.Tables[0]:
        //      查询得出的数据；   
        public DataTable loadDate(string sql)
        {
            DataSet dt = new DataSet();
            try
            {
                this.connet();
                SqlDataAdapter sap = new SqlDataAdapter(sql, conn);
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }
                    sap.Fill(dt);
            }
            catch (Exception ex)
            {
                //Time.Foramework.ConfigOperate.PrintLog(ex.Message);
                throw;
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
            if (dt.Tables.Count!=0)
            {
                return dt.Tables[0];
            }
            else
            {
                return null;
            }
        }
        #endregion
    }
}
